package com.czk;

import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * netty服务
 *
 * @Author:ChenZhangKun
 * @Date: 2021/4/5 22:33
 */
public class NettyServer {
    /**
     * 监听端口及服务
     *
     * @param host
     * @param port
     * @throws InterruptedException
     */
    public void start(String host, int port) throws InterruptedException {
        ServerBootstrap bootstrap = new ServerBootstrap();
        // 创建线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workgroup = new NioEventLoopGroup();
        bootstrap.group(bossGroup, workgroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 128)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 拿到管道
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast("decoder", new StringDecoder())
                                .addLast("encoder", new StringEncoder())
                                .addLast(new NettyServerHandler());
                    }
                });
        ChannelFuture sync = bootstrap.bind(host, port).sync();

    }
}
